/**
 * Check if an element has a class
 * @param {HTMLElement} ele
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele: HTMLElement, cls: string) {
  return !!ele.className.match(new RegExp("(\\s|^)" + cls + "(\\s|$)"));
}

/**
 * Add class to element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function addClass(ele: HTMLElement, cls: string) {
  if (!hasClass(ele, cls)) ele.className += " " + cls;
}

/**
 * Remove class from element
 * @param {HTMLElement} ele
 * @param {string} cls
 */
export function removeClass(ele: HTMLElement, cls: string) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp("(\\s|^)" + cls + "(\\s|$)");
    ele.className = ele.className.replace(reg, " ");
  }
}

/**
 * 判断是否是外部链接
 *
 * @param {string} path
 * @returns {Boolean}
 */
export function isExternal(path: string) {
  const isExternal = /^(https?:|http?:|mailto:|tel:)/.test(path);
  return isExternal;
}

/**
 * 格式化增长率，保留两位小数 ，并且去掉末尾的0  取绝对值
 *
 * @param growthRate
 * @returns
 */
export function formatGrowthRate(growthRate: number) {
  if (growthRate === 0) {
    return "-";
  }

  const formattedRate = Math.abs(growthRate * 100)
    .toFixed(2)
    .replace(/\.?0+$/, "");
  return formattedRate + "%";
}

/**
 * 将扁平化数据转换为树形结构
 * @param data 扁平化数据
 * @param idField ID字段名，默认为'id'
 * @param parentIdField 父ID字段名，默认为'parentId'
 * @param childrenField 子节点字段名，默认为'children'
 * @returns 树形结构数据
 */
export function buildMenuTree(
  data: any[],
  idField = "id",
  parentIdField = "parentId",
  childrenField = "children"
) {
  const tree: any[] = [];
  const childrenOf: { [key: string]: any[] } = {};

  data.forEach((item) => {
    const id = item[idField];
    const parentId = item[parentIdField];

    childrenOf[id] = childrenOf[id] || [];
    item[childrenField] = childrenOf[id];

    if (parentId === 0 || parentId === null || parentId === undefined) {
      tree.push(item);
    } else {
      childrenOf[parentId] = childrenOf[parentId] || [];
      childrenOf[parentId].push(item);
    }
  });
  return tree;
}
